package com.qing.springcloud.config.handle;
import cn.hutool.core.util.NumberUtil;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.serializer.StringCodec;

import java.lang.reflect.Type;

/**
 * @author caozhipeng
 * @date 2025/7/21
 */
public class StringCodeHandle  extends StringCodec{

    public static final StringCodeHandle instance = new StringCodeHandle();

    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
        final JSONLexer lexer = parser.lexer;
        if (clazz == StringBuffer.class) {
            if (lexer.token() == JSONToken.LITERAL_STRING) {
                String val = lexer.stringVal();
                lexer.nextToken(JSONToken.COMMA);
                return (T) new StringBuffer(val);
            }

            Object value = parser.parse();
            if (value == null) {
                return null;
            }
            return (T) new StringBuffer(value.toString());
        }

        if (clazz == StringBuilder.class) {
            if (lexer.token() == JSONToken.LITERAL_STRING) {
                String val = lexer.stringVal();
                lexer.nextToken(JSONToken.COMMA);
                return (T) new StringBuilder(val);
            }
            Object value = parser.parse();
            if (value == null) {
                return null;
            }
            return (T) new StringBuilder(value.toString());
        }

        String val = lexer.stringVal();
        // 16位以上的 uid 需要转换成Long 型
        if (val.length() > 16) {
            if (NumberUtil.isLong(val)) {
                return (T) Long.valueOf(NumberUtil.parseLong(val));
            }
        }

        return (T) deserialze(parser);
    }
}
